<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/6/9 0009
 * Time: 下午 2:51
 */

namespace DataAPI\Model;

use Think\Model;
class UserModel extends Model
{
    public $model;
    public $ErrMessage;
    public function __construct()
    {
        $this->model = M('data_users');
    }

    public function getError()
    {
        return $this->ErrMessage;
    }

    /**
     * 增加用户
     * @param $userInfo
     * @return bool
     */
    public function addUser($userInfo){

        if($newUserInfo = $this->userValidate($userInfo)){

            $result = $this->model->add($newUserInfo);
            if($result){
                return $result;
            }else{
                return false;
            }
        }
    }

    /**
     * 信息验证
     * @param $userInfo
     */
    public function userValidate($userInfo){
        if(empty($userInfo)){
            $this->ErrMessage = '传入参数错误';
            return false;
        }
        if(!isset($userInfo['username']) || empty($userInfo['username']) ){
            $this->ErrMessage = '用户名不能为空';
            return false;
        }
        if($this->getOne(['username'=>$userInfo['username']])){
            $this->ErrMessage = '用户名已经存在';
            return false;
        }
        if(!isset($userInfo['app_id']) || empty($userInfo['app_id']) ){
            $this->ErrMessage = '商户id不能为空';
            return false;
        }
        if($this->getOne(['app_id'=>$userInfo['app_id']])){
            $this->ErrMessage = '商户已经认证过，请勿重复认证';
            return false;
        }
        if(!isset($userInfo['app_key']) || empty($userInfo['app_key']) ){
            $this->ErrMessage = '商户密钥不能为空';
            return false;
        }
        if(!isset($userInfo['password']) || empty($userInfo['password']) ){
            $this->ErrMessage = '密码不能为空';
            return false;
        }
        if(preg_match("/^[^\u4e00-\u9fa5\s]{6,20}$/",$userInfo['password'])){
            $this->ErrMessage = '密码不能不能少于6位，或者使用了非法字符';
            return false;
        }
        $userInfo['password'] = md5(md5($userInfo['password']));
        $userInfo['createdtime'] = time();
        return $userInfo;
    }
    public function getOne($where){
        return $this->model->where($where)->select();
    }

    /**
     * 改密码
     * @param $data
     * @return bool
     */
    public function modifyPassword($data){
        $arr['password'] = md5(md5($data['password']));
        return $this->model->where(['username'=>$data['username']])->save($arr);
    }
}